package com.zws.cucumber.wiremock.datatable;

import io.cucumber.datatable.DataTable;
import io.cucumber.datatable.TableTransformer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ZwsMappingAndParametersTransformer implements TableTransformer<List<ZwsMappingAndParameters>> {

    @Override
    public List<ZwsMappingAndParameters> transform(DataTable table) throws Throwable {
        return table.cells()
                .stream()
                .reduce(new ArrayList<ZwsMappingAndParameters>(),
                        (List<ZwsMappingAndParameters> listOfTarget, List<String> listOfSource) -> {
                            if (listOfSource.get(0).startsWith("[mapping]")) {
                                String name = listOfSource.get(0).substring("[mapping]".length()).trim();
                                String mappingFile = listOfSource.get(1) == null ? null : listOfSource.get(1).trim();
                                listOfTarget.add(new ZwsMappingAndParameters(name, mappingFile, new HashMap<>()));
                            } else {
                                if (listOfSource.size() != 2) {
                                    throw new IllegalArgumentException();
                                }
                                if (listOfTarget.isEmpty()) {
                                    throw new IllegalStateException();
                                }
                                ZwsMappingAndParameters mappingAndParameters = listOfTarget.get(listOfTarget.size() - 1);
                                mappingAndParameters.getParameters().put(
                                        listOfSource.get(0).trim(),
                                        listOfSource.get(1) == null ? null : listOfSource.get(1).trim());
                            }
                            return listOfTarget;
                        }, (l, r) -> l);
    }

}
